package com.wyz.saas.common.set

import com.atom.api.ApiContext
import com.atom.api.ApiContextAware
import com.wyz.saas.api.set.AppSetDescriptor
import com.wyz.saas.api.set.AppSetter
import com.wyz.saas.common.utils.otherwise
import com.wyz.saas.common.utils.yes

abstract class AbstractAppSetDescriptor<T : Any> : ApiContextAware, AppSetDescriptor {

    protected lateinit var mApiContext: ApiContext

    protected var setter: AppSetter? = null
        get() {
            if (field == null) {
                field = mApiContext.getImpl(AppSetter::class.java)
            }
            return field
        }

    override fun setApiContextAware(context: ApiContext) {
        this.mApiContext = context
    }

    protected abstract fun default(): T

    protected abstract fun get(): T?

    protected abstract fun put(t: T)

    final override fun setValue(value: Any?) {
        validate(value).yes {
            put(value as T)
        }
    }

    final override fun getValue(): Any? {
        val get = get()
        validate(get).yes {
            return get
        }.otherwise {
            return default()
        }
    }
}